package com.debao.system.domain.wechat;

import com.debao.common.constant.WechatConstants;
import com.debao.common.wechat.WechatUtils;
import com.debao.system.service.IConfigService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 处理微信消息
 */
@Service
@Slf4j
public class WeChatMPServiceImpl implements WeChatMPService {

    @Autowired
    private WechatAccountService wechatAccountService;
    @Autowired
    private IConfigService configService;
    @Override
    public String processRequest(HttpServletRequest request) {
        // xml格式的消息数据
        String respXml = null;
        // 默认返回的文本消息内容
        String respContent = null;
        try {
            // 调用parseXml方法解析请求消息
            Map<String, String> requestMap = WechatUtils.parseXml(request);
            // 消息类型
            String msgType = requestMap.get(WechatConstants.MsgType);
            log.info("\n消息类型：{}", msgType);
            String mes = null;
            if (msgType.equals("event")) {
                // 事件类型
                String eventType = requestMap.get("Event");
                // 关注
                if (eventType.equals("subscribe")) {
                    wechatAccountService.subscribeMPUserInfo(requestMap.get(WechatConstants.FromUserName));
                    respContent = "您好！欢迎关注德宝乒乓公众号。在这里，我们将分享乒乓球技巧、比赛动态及训练心得，助您提升球技";
                    respXml = WechatUtils.sendTextMsg(requestMap, respContent);
                }
                // 取消关注
                else if (eventType.equals("unsubscribe")) {
                    wechatAccountService.unsubscribeMPUserInfo(requestMap.get(WechatConstants.FromUserName));
                }
            }
            mes = mes == null ? "客服暂时不在线，您可以拨打客服电话：15812488549进行咨询。" : mes;
            if (respXml == null) {
                respXml = WechatUtils.sendTextMsg(requestMap, mes);
            }
            log.info("\n"+respXml);
            return respXml;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}